import { createSlice } from "@reduxjs/toolkit";

export type ThemeType = "light" | "dark";
export enum ThemeEnum {
    light = 'light',
    dark = 'dark'
};

const getTheme = (): ThemeEnum => {
    const theme: ThemeEnum|null = window?.localStorage?.getItem("theme") as ThemeEnum|null;
    if (theme && ["light", "dark"].includes(theme)) return theme;

    const userMedia = window?.matchMedia("(prefers-color-scheme: light)");
    if (userMedia.matches) return ThemeEnum.light;

    return ThemeEnum.dark;
};

const initialState = getTheme();

export const themeSlice = createSlice({
    name: "theme",
    initialState,
    reducers: {
        set: (state, action) => action.payload,
    }
});

export const { set } = themeSlice.actions;

export default themeSlice.reducer;
